from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from goods.models import SKU
from carts.serializers import CartListSerializer
from rest_framework.generics import CreateAPIView
from .serializers import OrderCreateSerializer


class SettlementView(APIView):
    #要求登录
    permission_classes = [IsAuthenticated]

    def get(self,request):
        #聪redis中读取购物车数据据
        user = request.user
        #1.链接redis
        redis_cli = get_redis_connection('cart')

        #2.聪set中读取选中的商品sku_id
        sku_ids = redis_cli.smembers('cart_selected_%d' % user.id)
        sku_ids = [int(sku_id) for sku_id in sku_ids]
        #3.聪hash中读取所有商品sku_dict
        sku_dict = redis_cli.hgetall('cart_%d' % user.id)
        sku_dict = {int(sku_id):int(count) for sku_id,count in
                    sku_dict.items()}

        #遍4.历sku_ids，查询商品对象，为数量属性赋值
        skus = SKU.objects.filter(pk__in=sku_ids)
        for sku in skus:
            sku.count=sku_dict.get(sku.id)
            sku.selected = True

        #序列化输出
        serializer = CartListSerializer(skus,many=True)
        return Response({
            'freight':10,
            'skus':serializer.data
        })


class OrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCreateSerializer